//OrderServiceImpl.java
package com.ylaihui.service.impl;

import com.ylaihui.dao.BookDao;
import com.ylaihui.dao.OrderDao;
import com.ylaihui.dao.OrderItemDao;
import com.ylaihui.dao.impl.BookDaoImpl;
import com.ylaihui.dao.impl.OrderDaoImpl;
import com.ylaihui.dao.impl.OrderItemDaoImpl;
import com.ylaihui.pojo.*;
import com.ylaihui.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lisimmy www.ylaihui.com
 * @create 2021-08-03
 */
public class OrderServiceImpl implements OrderService {
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private OrderDao orderDao = new OrderDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        //生成订单号
        String orderId = System.currentTimeMillis() + "" + userId;

        //生成订单数据，保存到t_order表
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        orderDao.saveOrder(order);

        //将购物车中的商品项 转换为 订单中的订单项, 保存到t_order_items 表
        Map<Integer, CartItem> items = cart.getItems();

        for (Map.Entry<Integer, CartItem> entry : items.entrySet()) {
            CartItem value = entry.getValue();
            OrderItem orderItem = new OrderItem(null, value.getName(), value.getCount(), value.getPrice(), value.getTotalPrice(), orderId);
            //写入数据库中
            orderItemDao.saveOrderItem(orderItem);

            // 修改库存
            Book book = bookDao.queryBookById(value.getId());
            book.setSales(book.getSales() + value.getCount());
            book.setStock(book.getStock() - value.getCount());
            bookDao.updateBook(book);
        }
        // 购物车已经变为了订单， 购物车中的数据需要清空
        cart.clear();
        return orderId;
    }

    @Override
    public List<Order> showAllOrders() {
        List<Order> orders = orderDao.queryOrders();
        return orders;
    }

    @Override
    public Order queryOrderByOrderId(String orderId) {
        return orderDao.queryOrderByOrderId(orderId);
    }

    @Override
    public void sendOrder(String orderId) {
        orderDao.changeOrderStatus(orderId, 1);
    }

    @Override
    public List<OrderItem> showOrderDetails(String orderId) {
        List<OrderItem> orderItems = orderItemDao.queryOrderItemsByOrderId(orderId);
        return orderItems;
    }

    @Override
    public List<Order> showUserOrders(Integer userId) {
        List<Order> orders = orderDao.queryOrdersByUserId(userId);
        return orders;
    }
}
